<template>
  <!--任务管理  -->
  <div class="box-shadow">
    <!-- 搜索 -->
    <div class="search-area">
      <div class="form">
        <el-form
          :model="listQuery"
          ref="listQuery"
          size="small"
          :inline="true"
          label-width="123px"
        >
          <el-form-item :label="$t('任务名称') + ':'" prop="taskName">
            <el-input
              v-model="listQuery.taskName"
              :placeholder="$t('请输入')"
              clearable
              size="medium"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('任务类型') + ':'" prop="taskType">
            <el-select
              v-model="listQuery.taskType"
              clearable
              :placeholder="$t('请选择')"
              size="medium"
            >
              <el-option
                v-for="dict in dict.type.taskType"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('巡检类型') + ':'" prop="viewType">
            <el-select
              v-model="listQuery.viewType"
              clearable
              :placeholder="$t('请选择')"
              size="medium"
            >
              <el-option
                v-for="dict in dict.type.viewType"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item :label="$t('巡检维度') + ':'" prop="dimension">
            <el-select
              v-model="listQuery.dimension"
              clearable
              :placeholder="$t('请选择')"
              size="medium"
            >
              <el-option
                v-for="dict in dict.type.dimension"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item :label="$t('生效时段') + ':'" prop="dimension">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              size="medium"
              range-separator="-"
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="timeChange"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="优先级:">
            <el-checkbox-group v-model="listQuery.priorityList">
              <el-checkbox label="1">1级</el-checkbox>
              <el-checkbox label="2">2级</el-checkbox>
              <el-checkbox label="3">3级</el-checkbox>
              <el-checkbox label="4">4级</el-checkbox>
              <el-checkbox label="5">5级</el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
          <el-form-item :label="$t('生效状态') + ':'">
            <el-checkbox-group v-model="listQuery.validStatusList">
              <el-checkbox
                v-for="dict in dict.type.validStatus"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="search-area-btn btns">
        <div
          @click="serachBtn"
          class="serch-btn cursor-pointer"
          v-hasPermi="['task:manage:search']"
        >
          {{ $t("搜索") }}
        </div>
        <div
          @click="resetFormBtn()"
          class="reset-btn cursor-pointer"
          v-hasPermi="['task:manage:reset']"
        >
          {{ $t("重置") }}
        </div>
      </div>
    </div>
    <!-- 表格 -->
    <div class="table">
      <div class="self">
        <div class="search-area-btn btns">
          <div
            @click="addTaskBtn"
            class="serch-btn cursor-pointer table-top"
            v-hasPermi="['task:manage:add']"
          >
            {{ $t("新增任务") }}
          </div>
          <div
            @click="handleDelete('more', '')"
            class="btn-red cursor-pointer table-top"
            v-hasPermi="['task:manage:batchremove']"
          >
            {{ $t("批量删除") }}
          </div>
        </div>
        <el-table
          ref="tableRef"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%; margin-top: 16px"
          @selection-change="selectionChange"
        >
          <el-table-column align="center" type="selection"> </el-table-column>
          <el-table-column align="center" prop="taskId" :label="$t('任务ID')">
          </el-table-column>
          <el-table-column
            min-width="300"
            show-overflow-tooltip
            align="center"
            prop="taskName"
            :label="$t('任务名称')"
            width="180"
          >
          </el-table-column>
          <!-- <el-table-column align="center" prop="priority" label="任务优先级">
          </el-table-column> -->
          <el-table-column
            prop="taskType"
            :label="$t('任务类型')"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.taskType"
                :value="scope.row.taskType"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="viewType"
            :label="$t('巡检类型')"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.viewType"
                :value="scope.row.viewType"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="dimension"
            :label="$t('巡检维度')"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.dimension"
                :value="scope.row.dimension"
              />
            </template>
          </el-table-column> -->
          <el-table-column
            prop="validStatus"
            :label="$t('生效状态')"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.validStatus"
                :value="scope.row.validStatus"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="effectStartTime"
            :label="$t('生效开始时间')"
            show-overflow-tooltip
            align="center"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="effectEndTime"
            :label="$t('生效结束时间')"
            show-overflow-tooltip
            align="center"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="repeatRate"
            :label="$t('重复频率')"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.repeatRate }}</span>
              <dict-tag
                style="display: inline-block"
                :options="dict.type.repeatRateUnit"
                :value="scope.row.repeatRateUnit"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('操作')" width="200">
            <template slot-scope="scope">
              <div class="table-btns">
                <div
                  class="serch-btn cursor-pointer"
                  style="width: 70px"
                  :style="
                    scope.row.taskType != '1'
                      ? 'border-color:rgba(0, 209, 255, 0.2);background-color:rgba(0, 209, 255, 0.1);color:rgba(255, 255, 255, 0.1)'
                      : ''
                  "
                  @click="executedImmediately(scope.row)"
                  v-hasPermi="['task:manage:immediate']"
                >
                  {{ $t("立即执行") }}
                </div>
                <div
                  @click="editTaskBtn(scope.row)"
                  class="btn-green cursor-pointer"
                  style="width: 40px"
                  v-hasPermi="['task:manage:edit']"
                >
                  {{ $t("编辑") }}
                </div>
                <div
                  @click="handleDelete('less', scope.row)"
                  class="btn-red cursor-pointer"
                  style="width: 40px"
                  v-hasPermi="['task:manage:remove']"
                >
                  {{ $t("删除") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagenation">
        <pagination
          :total="total"
          :page.sync="listQuerySubmit.pageNum"
          :limit.sync="listQuerySubmit.pageSize"
          @pagination="getTableList"
        >
        </pagination>
      </div>
    </div>
    <!-- 立即执行弹框 -->
    <TaskDialog
      :taskDialog="taskVisible"
      :taskName="taskName"
      @taskDialogConfirm="dialogConfirm"
      @taskDialogCancle="dialogCancle"
    ></TaskDialog>
    <!-- 删除任务弹框 -->
    <TaskManageDialog
      :delDialog="delDialog"
      :taskName="taskNameList"
      :hasTaskName="hasTaskName"
      :transLength="transLength"
      :isMore="isMore"
      :isTasking="isTasking"
      @taskDialogConfirm="taskDialogConfirm"
      @taskDialogCancle="taskDialogCancle"
    ></TaskManageDialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import TaskDialog from "@/components/TaskDialog";
import {
  API_taskControl, //任务控制
} from "@/api/robot/monitor";
import { API_TaskList, API_delTask, API_ImmediateRun } from "@/api/task/manage";
import TaskManageDialog from "./components/TaskManageDialog.vue";
export default {
  dicts: ["taskType", "viewType", "dimension", "repeatRateUnit", "validStatus"],
  components: {
    TaskDialog,
    TaskManageDialog,
  },
  data() {
    return {
      delDialog: false, //删除弹框
      taskVisible: false, //任务dialog
      isMore: false, //是单选还是多选
      isTasking: false, //判断当前是否有正在执行的任务
      globalCurrentTaskId: "", //全局当前任务id
      globalCurrentExecId: "", //全局执行任务id
      globalCurrentTaskProcess: "", //当前任务进度
      taskName: "", //全局执行任务名称
      taskId: "", //立即执行的任务id
      transLength: 0, //多选length
      hasTaskName: "", //正在执行的任务名称
      taskIds: [], //被选中的删除的taskIds
      listQuery: {
        taskName: null,
        taskType: "",
        viewType: "",
        dimension: "",
        startTime: "",
        endTime: "",
        priorityList: [],
        validStatusList: [],
        pageNum: 1,
        pageSize: 10,
      },
      dateRange: [],
      total: 0,
      listQuerySubmit: {},
      tableData: [],
      selectionMore: [], // 选中数组
      selectionSingle: [], //只有taskid的数组
      single: true, // 非单个禁用
      taskNameList: "", //被选中的删除任务
      currentTaskTimer: null, //当前任务定时器
    };
  },
  computed: {
    ...mapGetters(["globalCurrentTaskInfo"]),
  },
  created() {
    this.listQuerySubmit = Object.assign({}, this.listQuery);
    this.getTableList();
  },
  mounted() {
    this.currentTaskTimer = setInterval(() => {
      this.getTaskInfo();
    }, 1000);
  },
  methods: {
    /**获取当前任务信息 */
    getTaskInfo() {
      this.$store.dispatch("getGlobalTaskInfo").then((res) => {
        if (res.code == 200 && res.data) {
          this.globalCurrentTaskId = JSON.parse(res.data).taskId; //任务ID
          this.globalCurrentTaskProcess = JSON.parse(res.data).taskProcess;
          this.globalCurrentExecId = JSON.parse(res.data).execId; //任务执行ID
          this.taskName = JSON.parse(res.data).taskName; //任务名称
        }
      });
    },
    /**重置 */
    resetFormBtn() {
      this.listQuery = {
        taskName: null,
        taskType: "",
        viewType: "",
        dimension: "",
        startTime: "",
        endTime: "",
        priorityList: [],
        validStatusList: [],
        pageNum: 1,
        pageSize: 10,
      };
      this.dateRange = [];
      this.serachBtn();
    },
    /**搜索 */
    serachBtn() {
      this.listQuery.pageNum = 1;
      this.listQuerySubmit = Object.assign({}, this.listQuery);
      this.getTableList();
    },
    /** table多选 */
    selectionChange(selection) {
      this.selectionMore = selection;
      this.selectionSingle = selection.map((item) => item.taskId);
      this.single = selection.length !== 1;
    },
    /** 批量删除按钮操作 */
    handleDelete(type, row) {
      this.taskIds = "";
      switch (type) {
        case "more":
          this.taskIds = this.selectionSingle;
          this.isMore = true;
          if (this.selectionMore.length == 0) {
            this.$message.info(this.$t("请选择需要批量删除的任务"));
            return;
          }
          this.delDialog = true; //处理弹框显隐
          this.transLength = this.selectionMore.length;
          if (
            this.globalCurrentTaskId != -1 &&
            this.selectionSingle.indexOf(Number(this.globalCurrentTaskId)) !==
              -1
          ) {
            // 有正在执行的任务
            this.isTasking = true;
            this.hasTaskName = this.globalCurrentTaskInfo.taskName;
          } else {
            //没有正在执行的任务
            this.isTasking = false;
          }
          break;
        case "less":
          this.delDialog = true; //处理弹框显隐
          this.taskIds = [row.taskId];
          this.isMore = false;
          this.taskNameList = row.taskName; //任务名称
          if (
            this.globalCurrentTaskId != -1 &&
            this.globalCurrentTaskId == row.taskId
          ) {
            // 有正在执行的任务
            this.isTasking = true;
            this.hasTaskName = this.globalCurrentTaskInfo.taskName;
          } else {
            // 没有正在执行的任务
            this.isTasking = false;
          }
          break;
      }
    },
    /**弹框内部取消 */
    taskDialogCancle() {
      this.delDialog = false;
    },
    /**弹框确认按钮 */
    taskDialogConfirm() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // 有任务正在执行
      if (this.isTasking == true) {
        // 终止正在执行的
        API_taskControl({
          cmd: "3X13",
          values: [this.globalCurrentTaskId, this.globalCurrentExecId],
        })
          .then((res) => {
            if (res.code == 200 && res.data.nerrcode == 0) {
              this.$message({
                type: "success",
                message: this.$t("任务已强制终止"),
              });
            } else {
              this.$message.error(this.$t("终止失败请重试"));
            }
          })
          .finally(() => {
            this.serachBtn();
            this.delDialog = false;
            loading.close();
          });
        //如果是多个  删除其余的
        if (this.taskIds.length > 1) {
          const loadingmore = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //筛选出额外的
          let taskIds = this.taskIds.filter((item) => {
            return item != this.globalCurrentTaskId;
          });
          API_delTask(taskIds)
            .then((res) => {
              if (res.code == 200) {
                this.delDialog = false;
                this.$message.success(this.$t("删除成功"));
                this.serachBtn();
              }
            })
            .finally(() => {
              loadingmore.close();
            });
        }
      } else {
        //没有正在执行任务  删除
        API_delTask(this.taskIds)
          .then((res) => {
            if (res.code == 200) {
              this.delDialog = false;
              this.$message.success(this.$t("删除成功"));
              this.serachBtn();
            }
          })
          .finally(() => {
            loading.close();
          });
      }
    },
    /**任务管理列表 */
    getTableList() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // 优先级
      let priorityList = this.listQuerySubmit.priorityList;
      if (priorityList && priorityList.length > 0) {
        if (priorityList.indexOf(",") == -1) {
          priorityList = String(priorityList);
        } else {
          priorityList = priorityList.join(",");
        }
      }
      // 生效状态
      let validStatusList = this.listQuerySubmit.validStatusList;
      if (validStatusList && validStatusList.length > 0) {
        if (validStatusList.indexOf(",") == -1) {
          validStatusList = String(validStatusList);
        } else {
          validStatusList = validStatusList.join(",");
        }
      }
      API_TaskList({
        ...this.listQuerySubmit,
        priorityList: priorityList,
        validStatusList: validStatusList,
      })
        .then((res) => {
          if (res.code == 200) {
            if (res.rows.length > 0) {
              this.tableData = res.rows;
            } else {
              this.tableData = [];
            }
            this.total = Number(res.total);
            this.listQuery = Object.assign({}, this.listQuerySubmit);
          }
        })
        .finally(() => {
          loading.close();
        });
    },
    /**新增任务 */
    addTaskBtn() {
      this.$router.push({
        path: "/manage/addManage",
        query: {},
      });
    },
    /**编辑任务 */
    editTaskBtn(row) {
      this.$router.push({
        path: "/manage/editManage",
        query: {
          id: row.taskId,
        },
      });
    },
    /**取消 */
    dialogCancle() {
      this.taskVisible = false;
    },
    /**立即执行弹框内部确认 */
    dialogConfirm(radioVal) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (radioVal == 1) {
        //暂停当前任务
        API_taskControl({
          cmd: "3X12",
          values: [this.globalCurrentTaskId, this.globalCurrentExecId],
        })
          .then((res) => {
            if (res.code == 200 && res.data.nerrcode == 0) {
              this.$message({
                type: "success",
                message: this.$t('"任务已暂停"'),
              });
              //执行当前任务
              API_ImmediateRun(this.taskId).then((res) => {
                if (res.code == 200) {
                  this.$message.success(this.$t("立即执行成功"));
                  this.serachBtn();
                }
              });
            } else {
              this.$message.error(this.$t("暂停失败请重试"));
            }
          })
          .finally(() => {
            loading.close();
            this.taskVisible = false;
          });
      } else if (radioVal == 2) {
        //终止当前任务
        API_taskControl({
          cmd: "3X13",
          values: [this.globalCurrentTaskId, this.globalCurrentExecId],
        })
          .then((res) => {
            if (res.code == 200 && res.data.nerrcode == 0) {
              this.$message({
                type: "success",
                message: this.$t("任务已终止"),
              });
              //执行当前任务
              API_ImmediateRun(this.taskId).then((res) => {
                if (res.code == 200) {
                  this.$message.success(this.$t("立即执行成功"));
                  this.serachBtn();
                }
              });
            } else {
              this.$message.error(this.$t("终止失败请重试"));
            }
          })
          .finally(() => {
            loading.close();
            this.taskVisible = false;
          });
      } else {
        //继续当前任务
      }
    },
    /**立即执行 */
    executedImmediately(row) {
      if (row.taskType != "1") {
        return;
      }
      this.taskId = row.taskId;
      // 判断是否有正在执行的任务
      if (
        this.globalCurrentTaskId != -1 &&
        this.globalCurrentTaskProcess == "3"
      ) {
        //展示弹框
        this.taskVisible = true;
      } else {
        this.$confirm(this.$t("确认要立即执行是否继续"), this.$t("执行确认"), {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        })
          .then(() => {
            API_ImmediateRun(row.taskId).then((res) => {
              if (res.code == 200) {
                this.$message.success(this.$t("立即执行成功"));
                this.serachBtn();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t("已取消"),
            });
          });
      }
    },
    /**时间 change事件 */
    timeChange() {
      if (this.dateRange) {
        this.listQuery.startTime = this.dateRange[0];
        this.listQuery.endTime = this.dateRange[1];
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    },
  },
  beforeDestroy() {
    clearInterval(this.currentTaskTimer);
    this.currentTaskTimer = null;
  },
};
</script>
<style lang="scss" scoped>
.table {
  width: 100%;
  height: 770px;
  // margin-top: 16px;
  border-top: 1px dashed rgba(219, 255, 251, 0.2);
  padding: 24px;
  box-sizing: border-box;
  position: relative;
  .btns {
    display: flex;
    width: 100%;
    justify-content: flex-start;
    div:nth-child(2) {
      margin: 0 16px;
    }
  }
  .table-btns {
    display: flex;
    div {
      display: flex;
      // width: 46px;
      height: 28px;
      justify-content: center;
      align-items: center;
      font-size: 12px;
    }
    div:nth-child(2),
    div:nth-child(4) {
      margin: 0 10px;
    }
    div:nth-child(5) {
      margin-right: 10px;
    }
  }
  .pagenation {
    position: absolute;
    bottom: 30px;
    right: 20px;
  }
}
::v-deep {
  .el-range-input {
    background-color: transparent;
    color: #fff;
  }
  .el-range-separator {
    color: #fff;
  }
  .self {
    .el-table__body-wrapper {
      width: 100%;
      max-height: 531px;
      overflow: auto;
    }
  }
}
</style>
